package com.local.web.controller;

import com.local.cart.pojo.ShoppingCart;
import com.local.common.constants.BusinessException;
import com.local.common.util.ResultUtil;
import com.local.coupon.feign.CouponServiceFeign;
import com.local.coupon.pojo.UserCouponRecord;
import com.local.coupon.pojo.UserCouponRecordListRequestParam;
import com.local.user.pojo.User;
import com.local.web.constants.WebConstants;
import com.local.web.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;

/**
 * 购物车控制器
 */
@Controller
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private CouponServiceFeign couponServiceFeign;


    /**
     * 购物车页面
     * @param request
     * @return
     */
    @GetMapping("/cart")
    public String index(HttpServletRequest request) {
        //查询session User用户对象信息
        User user = (User) request.getSession().getAttribute(WebConstants.WEB_USER_SESSION_KEY);

        //查询用户的购物车列表
        List<ShoppingCart> myShoppingCartItems = shoppingCartService.getListByUserId(request.getSession(), user.getUserId());
        Integer itemsTotal = 0;
        Integer priceTotal = 0;
        if (myShoppingCartItems.size() > 0) {
//            itemsTotal = myShoppingCartItems.stream().mapToInt(ShoppingCart::getGoodsCount).sum();
            itemsTotal = myShoppingCartItems.stream().mapToInt(new ToIntFunction<ShoppingCart>() {
                @Override
                public int applyAsInt(ShoppingCart value) {
                    return value.getGoodsCount();
                }
            }).sum();
            priceTotal = myShoppingCartItems.stream().mapToInt(new ToIntFunction<ShoppingCart>() {
                @Override
                public int applyAsInt(ShoppingCart value) {
                    return value.getGoodsCount() * value.getSellingPrice();
                }
            }).sum();
//            for (ShoppingCart myShoppingCartItem : myShoppingCartItems) {
//                itemsTotal += myShoppingCartItem.getGoodsCount();
//                priceTotal += myShoppingCartItem.getGoodsCount() * myShoppingCartItem.getSellingPrice();
//            }
        }

        request.setAttribute("myShoppingCartItems", myShoppingCartItems);
        request.setAttribute("itemsTotal", itemsTotal);
        request.setAttribute("priceTotal", priceTotal);
        request.setAttribute("path", "cart");

        return "mall/cart";
    }


    /**
     * 加入购物车
     * @param shoppingCart
     * @param session
     * @return
     */
    @PostMapping("/cart/add")
    @ResponseBody
    public ResultUtil add(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
        User user = (User) session.getAttribute(WebConstants.WEB_USER_SESSION_KEY);
        shoppingCart.setUserId(user.getUserId());
        return shoppingCartService.addToCart(session, shoppingCart);
    }


    /**
     * 在购物车页面，删除某个商品
     * @return
     */
    @DeleteMapping("/cart/{cartItemId}")
    @ResponseBody
    public ResultUtil delete(@PathVariable("cartItemId") Integer cartItemId, HttpSession session) {
        ResultUtil result = shoppingCartService.deleteByCartItemId(session, cartItemId);
        return result;
    }


    /**
     * 在购物车页面，修改商品数量
     * @return
     */
    @PutMapping("/cart")
    @ResponseBody
    public ResultUtil updateGoodsCount(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
        User user = (User) session.getAttribute(WebConstants.WEB_USER_SESSION_KEY);
        shoppingCart.setUserId(user.getUserId());
        return shoppingCartService.updateGoodsCount(session, shoppingCart);
    }


    /**
     * 填写并核对订单信息 页面
     * @param request
     * @return
     */
    @GetMapping("/cart/check")
    public String check(HttpServletRequest request) {
        //从session查询用户登录信息
        User user = (User) request.getSession().getAttribute(WebConstants.WEB_USER_SESSION_KEY);

        //查询用户的购物车列表
        List<ShoppingCart> shoppingCartList = shoppingCartService.getListByUserId(request.getSession(), user.getUserId());
        if (shoppingCartList.isEmpty()) {
            return "redirect:/cart";
        }

        //购物车商品总价
        Integer priceTotal = shoppingCartList.stream().mapToInt(ShoppingCart::getSellingPrice).sum();
        //用户的购物券
        List<Integer> goodsIdList = shoppingCartList.stream().map(ShoppingCart::getGoodsId).collect(Collectors.toList());
        UserCouponRecordListRequestParam requestParam = new UserCouponRecordListRequestParam(user.getUserId(), priceTotal, goodsIdList);
        ResultUtil<List<UserCouponRecord>> listResult = couponServiceFeign.getListForPay(requestParam);
        if (listResult.getCode() != 200) {
            throw new BusinessException(listResult.getCode(), listResult.getMessage());
        }
        List<UserCouponRecord> userCouponList = listResult.getData();

        request.setAttribute("coupons", userCouponList);
        request.setAttribute("priceTotal", priceTotal);
        request.setAttribute("myShoppingCartItems", shoppingCartList);

        return "mall/cart-check";
    }
}
